// Learn cc.Class:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/life-cycle-callbacks.html

cc.Class({
    extends: cc.Component,

    properties: {
        audioSource :cc.AudioSource,
        hitClip :cc.AudioClip,
        bombClip: cc.AudioClip,
        coinClip : cc.AudioClip
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        this.hitTime = 0;
        this.bombTime = 0;
        this.coinTime = 0;
        this.lastSound = -1;
        this.schedule(this._play.bind(this),0.1)
        cc.game.on(cc.game.EVENT_HIDE,()=>{
            this.audioSource.stop();
        })
        var self = this;
        cc.loader.loadRes('Audio/bomb5',cc.AudioClip,function(err,res){
            self.bombClip = res;
        })
        cc.loader.loadRes('Audio/hit',cc.AudioClip,function(err,res){
            self.hitClip = res;
        })
        cc.loader.loadRes('Audio/coin_get',cc.AudioClip,function(err,res){
            self.coinClip = res;
        })
    },
    onDestroy(){
        cc.game.off(cc.game.EVENT_HIDE)
    },
    _playClip(id,clip,force=false){
        if(this.lastSound == id){
            return;
        }
        if(force || this.lastSound != id){
            this.audioSource.stop();
        }
        this.audioSource.clip = clip;
        this.audioSource.loop = true
        this.lastSound = id;
        this.audioSource.play();
    },
    _play(dt){
        var isPlay = false;
        if(this.bombTime>0){
            this.bombTime -= dt;
            // !isPlay && this._playClip(1,this.bombClip)
            isPlay = true;
        }
        if(this.coinTime>0){
            this.coinTime -= dt;
            this._playClip(1,this.coinClip)
            this.audioSource.loop = false
            isPlay = true;
        }
        if(this.hitTime>0){
            this.hitTime -= dt;
            !isPlay && this._playClip(2,this.hitClip,true)
            isPlay = true;
        }
        !isPlay && (this.audioSource.stop(), this.lastSound = -1);
    },
    playHit(){
        this.hitTime = 0.1
    },
    playBomb(){
        this.bombTime = 0.4
        this.audioSource.stop();
        this.lastSound = 0;
        let as = new cc.AudioSource();
        as.volume = 0.6
        as.clip = this.bombClip;
        as.play();
        this.scheduleOnce(function(){
            as.stop();
        },0.6)
    },
    playCoin(){
         this.coinTime = 0.2
    }
});
